#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
from logging import handlers
from typing import Text
import colorlog
import time
from common.setting import ensure_path_sep
import os


class SingletonMeta(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]


class LogHandler(metaclass=SingletonMeta):
    """日志打印封装"""

    # 日志级别关系映射
    level_relations = {
        "debug": logging.DEBUG,
        "info": logging.INFO,
        "warning": logging.WARNING,
        "error": logging.ERROR,
        "critical": logging.CRITICAL,
    }

    def __init__(
        self,
        level: Text = "info",
        when: Text = "D",
        fmt: Text = "[%(asctime)s] [%(filename)s:%(lineno)s] [%(levelname)s]: %(message)s",
    ):
        now_time_day = time.strftime("%Y-%m-%d", time.localtime())
        log_folder = ensure_path_sep("\\logs")
        if not os.path.exists(log_folder):
            os.makedirs(log_folder)
        filename = os.path.join(log_folder, f"{now_time_day}.log")

        self.logger = logging.getLogger(filename)
        self.logger.propagate = False  # 添加此行，禁止传播到根日志器

        formatter = self.log_color()

        # 设置日志格式
        format_str = logging.Formatter(fmt)
        # 设置日志级别
        self.logger.setLevel(self.level_relations.get(level, logging.INFO))

        # 检查并添加 StreamHandler
        has_stream_handler = False
        for handler in self.logger.handlers:
            if isinstance(handler, logging.StreamHandler):
                has_stream_handler = True
                break
        if not has_stream_handler:
            # 往屏幕上输出
            screen_output = logging.StreamHandler()
            # 设置屏幕上显示的格式
            screen_output.setFormatter(formatter)
            self.logger.addHandler(screen_output)

        # 检查并添加 TimedRotatingFileHandler
        has_file_handler = False
        for handler in self.logger.handlers:
            if isinstance(handler, handlers.TimedRotatingFileHandler):
                has_file_handler = True
                break
        if not has_file_handler:
            # 往文件里写入#指定间隔时间自动生成文件的处理器
            time_rotating = handlers.TimedRotatingFileHandler(
                filename=filename, when=when, backupCount=3, encoding="utf-8"
            )
            # 设置文件里写入的格式
            time_rotating.setFormatter(format_str)
            self.logger.addHandler(time_rotating)

    @classmethod
    def log_color(cls):
        """设置日志颜色"""
        log_colors_config = {
            "DEBUG": "cyan",
            "INFO": "green",
            "WARNING": "yellow",
            "ERROR": "red",
            "CRITICAL": "red",
        }

        formatter = colorlog.ColoredFormatter(
            "%(log_color)s [%(asctime)s] [%(filename)s:%(lineno)s] [%(levelname)s]: %(message)s",
            log_colors=log_colors_config,
        )
        return formatter


logger = LogHandler().logger
